<?php

class EmailController extends AppController {

    public $uses = array('GroundRequestSchedule', 'GroundRequestScheduleAttachment');
    public $components = array('Email', 'Pdf');

    private function configureSMTP() {
        /* SMTP Options */
        $this->Email->smtpOptions = array(
            'port' => Configure::read('smtp_port'),
            'timeout' => Configure::read('smtp_timeout'),
            'host' => Configure::read('smtp_host'),
            'username' => Configure::read('smtp_username'),
            'password' => Configure::read('smtp_password'),
        );

        /* Set delivery method */
        $this->Email->delivery = 'smtp';
    }

    public function setEmailParameters($params = array()) {

        $this->configureSMTP();

        $default = array(
            'from' => 'S.B. MAN & Co. <icewalker2g@gmail.com>',
            'to' => array('Francis Adu-Gyamfi <fadu-gyamfi@infonaligy.com>'),
            'cc' => array(),
            'bcc' => array(), //array('Francis Adu-Gyamfi <icewalker2g@gmail.com>', "Nuku Ameyibor <nayibor@gmail.com>"),
            'subject' => 'Sample Email Subject',
            'replyTo' => 'S.B. Man & Co. <fltops@gsbmangh.com>',
            'message' => ''
        );

        $params = array_merge($default, $params);
        
        function checkAddressFormat($addresses) {
            if( is_string($addresses) ) {
                $addresses = explode(",", $addresses);
            }
            
            $formatted = array();
            if( is_array($addresses) ) {
                foreach($addresses as $address) {
                    if( strstr($address, "<") && strstr($address, ">") ) {
                        $formatted[] = $address;
                    }
                    
                    else {
                        $formatted[] = "$address <$address>";
                    }
                }
            }
            
            return $formatted;
        }

        $this->Email->to = checkAddressFormat($params['to']);
        $this->Email->cc = checkAddressFormat($params['cc']);
        $this->Email->bcc = checkAddressFormat($params['bcc']);
        $this->Email->subject = $params['subject'];
        $this->Email->replyTo = $params['replyTo'];
        $this->Email->from = $params['from'];

        //Send as 'html', 'text' or 'both' (default is 'text')
        $this->Email->sendAs = 'both'; // because we like to send pretty mail
        $this->Email->template = "empty_message";

        $this->set('message', $params['message']);
    }

    public function admin_sendHandlingRequest() {
        $this->autoRender = false;

        $this->setEmailParameters(array(
            'to' => $_POST['to'],
            'cc' => !empty($_POST['cc']) ? array($_POST['cc']) : array(),
            'subject' => $_POST['subject'],
            'message' => $_POST['message']
        ));

        if (isset($_POST['schedule_attachments'])) {
            $attachments = $this->GroundRequestScheduleAttachment->find('all', array(
                'conditions' => array(
                    'GroundRequestScheduleAttachment.id' => $_POST['schedule_attachments']
                ),
                'contain' => array(
                    'GroundRequestSchedule' => array(
                        'fields' => array('ref_no')
                    )
                )
            ));

            foreach ($attachments as $attachment) {
                $filename = $attachment['GroundRequestScheduleAttachment']['file_name'];
                $path = TMP . $attachment['GroundRequestSchedule']['ref_no'] . "-" . $attachment['GroundRequestScheduleAttachment']['file_name'];
                file_put_contents($path, $attachment['GroundRequestScheduleAttachment']['attachment']);

                $this->Email->attachments[$filename] = $path;
            }
        }
        
        $grs = new GroundRequestSchedule($_POST['schedule_id']);
        $ref_no = $grs->field('ref_no');

        if (isset($_POST['attach_handling_request'])) {
            $this->Email->attachments["handling_request_{$ref_no}.pdf"] = $this->Pdf->generate("handling_request_{$ref_no}.pdf", '/elements/ground/handling_request_form', array(
                'schedule_ids' => $_POST['schedule_id']
                    ));
        }

        if (isset($_POST['attach_qcr'])) {
            $this->Email->attachments["quality_request_{$ref_no}.pdf"] = $this->Pdf->generate("quality_request_{$ref_no}.pdf", '/elements/ground/quality_service_request', array(
                'schedule_id' => $_POST['schedule_id']
                    ));
        }

        if (isset($_POST['attach_jobsheet'])) {
            $this->Email->attachments["jobsheet_{$ref_no}.pdf"] = $this->Pdf->generate("jobsheet_{$ref_no}.pdf", '/elements/ground/jobsheet_summary_handler', array(
                'schedule_id' => $_POST['schedule_id']
                    ));
        }

        if (isset($_POST['attach_crew_brief'])) {
            $this->Email->attachments["crew_brief_{$ref_no}.pdf"] = $this->Pdf->generate("crew_brief_{$ref_no}.pdf", '/elements/ground/crew_brief_summary', array(
                'schedule_id' => $_POST['schedule_id']
                    ));
        }

        /* Do not pass any args to send() */
        if ($this->Email->send()) {

            $user = $this->Session->read('user');

            $grs = new GroundRequestSchedule($_POST['schedule_id']);
            $grs->set(array(
                'request_sent_dt' => date('Y-m-d H:i:s'),
                'request_sent_by' => $user['User']['id']
            ));
            $grs->save();

            echo json_encode(array('result' => 'success'));
        } else {
            echo json_encode(array('result' => 'failed', 'error' => $this->Email->smtpError));
        }
    }

    public function admin_issue_report() {

        if (isset($_POST['to']) && isset($_POST['cc'])) {
            $this->autoRender = false;

            $this->setEmailParameters(array(
                'to' => $_POST['to'],
                'cc' => !empty($_POST['cc']) ? array($_POST['cc']) : array(),
                'subject' => $_POST['subject'],
                'message' => $_POST['message']
            ));

            /**
             * We'll keep a copy of the issue locally so we can check if the issue was sent successfully later 
             */
            $user = $this->Session->read('user');
            $bugReport = ClassRegistry::init('BugReport');

            $bugReport->set(array(
                'user_id' => $user['User']['id'],
                'subject' => $_POST['subject'],
                'details' => $_POST['message'],
                'report_dt' => date('Y-m-d H:i:s'),
                'status' => 'pending'
            ));
            $bugReport->save();

            /* Do not pass any args to send() */
            if ($this->Email->send()) {

                $bugReport->set(array('status' => 'open'));
                $bugReport->save();

                echo json_encode(array('result' => 'success'));
            } else {
                echo json_encode(array('result' => 'failed', 'error' => $this->Email->smtpError));
            }
        }
    }

    public function admin_sendPermitRequestForm() {

        $this->autoRender = false;

        $this->setEmailParameters(array(
            'to' => $_POST['to'],
            'cc' => !empty($_POST['cc']) ? array($_POST['cc']) : array(),
            'subject' => $_POST['subject'],
            'message' => $_POST['message']
        ));

        if (isset($_POST['attach_request_form'])) {

            $user = $this->Session->read('user');
            $permit = ClassRegistry::init('Permit')->getForRequestFormPrint($_POST['permit_id']);
            $supervisor = ClassRegistry::init('DepartmentSupervisor')->getSupervisor($user);

            $this->Email->attachments["request_form_{$permit['Permit']['ref_no']}.pdf"] = $this->Pdf->generate(
                    "request_form_{$permit['Permit']['ref_no']}.pdf", '/elements/permits/request_form_content', array('permit' => $permit, 'supervisor' => $supervisor)
            );
        }

        /* Do not pass any args to send() */
        if ($this->Email->send()) {

            echo json_encode(array('result' => 'success'));
        } else {
            echo json_encode(array('result' => 'failed', 'error' => $this->Email->smtpError));
        }
    }
    
    public function admin_sendPermitForwardingForm() {

        $this->autoRender = false;

        $this->setEmailParameters(array(
            'to' => $_POST['to'],
            'cc' => !empty($_POST['cc']) ? array($_POST['cc']) : array(),
            'subject' => $_POST['subject'],
            'message' => $_POST['message']
        ));

        if (isset($_POST['attach_forwarding_form'])) {
            
            $user = $this->Session->read('user');
            $permit = ClassRegistry::init('Permit')->find('first', array('conditions' => array('id' => $_POST['permit_id']), 'recursive' => -1));
            $supervisor = ClassRegistry::init('DepartmentSupervisor')->getSupervisor($user);

            $this->Email->attachments["forwarding_form_{$permit['Permit']['ref_no']}.pdf"] = $this->Pdf->generate(
                    "forwarding_form_{$permit['Permit']['ref_no']}.pdf", '/elements/permits/forwarding_form_content', array('permit' => $permit, 'supervisor' => $supervisor, 'staff' => $user)
            );
        }

        /* Do not pass any args to send() */
        if ($this->Email->send()) {

            echo json_encode(array('result' => 'success'));
        } else {
            echo json_encode(array('result' => 'failed', 'error' => $this->Email->smtpError));
        }
    }
    
    public function admin_sendFuelRequestForm() {

        $this->autoRender = false;

        $this->setEmailParameters(array(
            'to' => $_POST['to'],
            'cc' => !empty($_POST['cc']) ? array($_POST['cc']) : array(),
            'subject' => $_POST['subject'],
            'message' => $_POST['message']
        ));

        if (isset($_POST['attach_request_form'])) {
            
            $user = $this->Session->read('user');
            $request = ClassRegistry::init('FuelRequest')->find('first', array('conditions' => array('id' => $_POST['request_id']), 'recursive' => -1));

            $this->Email->attachments["request_form_{$request['FuelRequest']['ref_no']}.pdf"] = $this->Pdf->generate("fuel_request_form_{$request['FuelRequest']['ref_no']}.pdf", 
                    '/elements/fuel/request_content', array('request' => $request, 'show_footer' => true, 'staff' => $user));
        }

        /* Do not pass any args to send() */
        if ($this->Email->send()) {

            echo json_encode(array('result' => 'success'));
        } else {
            echo json_encode(array('result' => 'failed', 'error' => $this->Email->smtpError));
        }
    }
    
    public function admin_sendFuelRequestConfirmation() {

        $this->autoRender = false;

        $this->setEmailParameters(array(
            'to' => $_POST['to'],
            'cc' => !empty($_POST['cc']) ? array($_POST['cc']) : array(),
            'subject' => $_POST['subject'],
            'message' => $_POST['message']
        ));

        if (isset($_POST['attach_request_form'])) {
            
            $user = $this->Session->read('user');
            $request = ClassRegistry::init('FuelRequest')->find('first', array('conditions' => array('id' => $_POST['request_id']), 'recursive' => -1));

            $this->Email->attachments["request_confirmation_form_{$request['FuelRequest']['ref_no']}.pdf"] = $this->Pdf->generate("fuel_request_confirmation_{$request['FuelRequest']['ref_no']}.pdf", 
                    '/elements/fuel/request_confirmation_content', array('request' => $request, 'show_footer' => true, 'staff' => $user));
        }

        /* Do not pass any args to send() */
        if ($this->Email->send()) {

            echo json_encode(array('result' => 'success'));
        } else {
            echo json_encode(array('result' => 'failed', 'error' => $this->Email->smtpError));
        }
    }

    public function testRF($permit_id) {
        $this->autoRender = false;

        $user = $this->Session->read('user');
        $permit = ClassRegistry::init('Permit')->getForRequestFormPrint($permit_id);
        $supervisor = ClassRegistry::init('DepartmentSupervisor')->getSupervisor($user);

        echo $this->Pdf->generate('request_form.pdf', '/elements/permits/request_form_content', array(
            'permit' => $permit,
            'supervisor' => $supervisor
        ));
    }
    
    public function testFF($permit_id) {
        $this->autoRender = false;
        
        $user = $this->Session->read('user');
        $permit = ClassRegistry::init('Permit')->find('first', array('conditions' => array('id' => $permit_id), 'recursive' => -1));
        $supervisor = ClassRegistry::init('DepartmentSupervisor')->getSupervisor($user);

        echo $this->Pdf->generate('forwarding_form.pdf', '/elements/permits/forwarding_form_content', array(
            'permit' => $permit,
            'supervisor' => $supervisor,
            'staff' => $user
        ));
    }

}

?>
